package com.luoshi.common.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @ClassName Result
 * @Description:统一返回结果类
 * @Author luochangqin
 * @Date 2021/5/16
 * @Version V1.0
 **/
@Data
@ApiModel(value = "全局统一返回结果")
public class Result<T> {

    @ApiModelProperty(value = "响应状态码")
    private Integer code;
    @ApiModelProperty(value = "错误消息")
    private String message;
    @ApiModelProperty(value = "响应数据")
    private T data;

    private Result(){
    }

    protected static <T> Result<T> build(T data) {
        Result<T> result = new Result<T>();
        if (data != null)
            result.setData(data);
        return result;
    }
    public static <T> Result<T> build(T body,ResultCodeEnum resultCodeEnum){
        Result<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return  result;
    }
    public static <T> Result<T> build(Integer code, String message) {
        Result<T> result = build(null);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }


    public static <T> Result<T> success(T data){
       Result<T> result = build(data);
       return build(data,ResultCodeEnum.SUCCESS);

    }
    public static <T> Result<T> success(){
        return Result.success(null);
    }


    public static<T> Result<T> fail(T data){
        Result<T> result = build(data);
        return build(data, ResultCodeEnum.FAIL);
    }
    public static<T> Result<T> fail(){
        return Result.fail(null);
    }
    public Result<T> message(String msg){
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code){
        this.setCode(code);
        return this;
    }

    public boolean isOk() {
        if(this.getCode().intValue() == ResultCodeEnum.SUCCESS.getCode().intValue()) {
            return true;
        }
        return false;
    }

    public static <T> Result<T> error(Integer code,String msg){
        return build(code,msg);
    }
}
